import {Component, OnDestroy, OnInit} from '@angular/core';
import {Message} from "../../../../model/Message";
import {CallcenterService} from "../../../../services/callcenter.service";
import {Router} from "@angular/router";
import {WebSocketSubject} from "rxjs/internal/observable/dom/WebSocketSubject";
import {webSocket} from "rxjs/webSocket";
import {delay, interval, retryWhen, take} from "rxjs";


@Component({
  selector: 'app-chatroom',
  templateUrl: './chatroom.component.html',
  styleUrls: ['./chatroom.component.css']
})
export class ChatroomComponent implements OnInit ,OnDestroy {
  ml: Array<Message>;
  socket$: any;
  msgtext: string;
  WS_ENDPOINT = "ws://192.168.2.66:2066/callcenter";
  sendping$:any;

  constructor(private callservice: CallcenterService
    , private router: Router) {
    this.ml = new Array<Message>();
    //this.init()

  }

  ngOnInit(): void {
    this.init()
  }

  sendMsg() {
    let msg = new Message();
    msg.type = 'chat';
    msg.fromuserid = 'user1';
    msg.content = this.msgtext;
    this.socket$.next(msg)
    this.msgtext = '';
  }

  ngOnDestroy(): void {

    this.onBack();
  }

  init() {
    if (!this.socket$ || this.socket$.closed){
      this.getNewWebSocket()
        .then((data:any)=>{
          if(data){
            this.socket$=data;
            this.socket$
              .pipe(
                retryWhen(errors => errors.pipe(delay(1000), take(2))),
              )
              .subscribe((m:Message)=>{
                this.ml.push(m);
              })

            this.sendping$=interval(6*60*1000)
              .subscribe(()=>{
                this.sendping()
              })

          }
        })
    }

  }




  onBack(){
    this.sendping$.complete();
      this.socket$.complete();
      this.router.navigate(['/welcome'])
  }



  private async getNewWebSocket() :Promise<WebSocketSubject<any>>{
    //console.log('条件触发');
    return webSocket({url:this.WS_ENDPOINT,
      deserializer:({data})=>{
        let m=new Message();
        // console.log(data);
        m=JSON.parse(data)
        return m;
      }
      //closeObserver:(event:any)=>this.closeedConnect()
    });


  }


  sendping(){
    let msg = new Message();
    msg.type = 'PING';
    msg.fromuserid = 'user1';
    this.socket$.next(msg)

  }



  sendRegist(){
    let msg=new Message();
    msg.type='REGIST';

  }


}
